//
//  PKCameraUtils.swift
//  Panku
//
//  Created by mac on 2017/2/15.
//  Copyright © 2017年 Monster. All rights reserved.
//

import UIKit
import GPUImage
import AVKit
import Photos
import SRGMediaPlayer

//enum PKFilter{
//    case F1997
//    case amaro
//    case brannan
//    case earlybird
//    case hefe
//    case hudson
//    case image
//    case inkwell
//    case lomofi
//    case lordKelvin
//    case nashville
//    case normal
//    case rise
//    case sierra
//    case sutro
//    case toaster
//    case valencia
//    case walden
//    case xproll
//}

class PKCameraUtils: NSObject {
    
    //单利
//    static let sharedInstanceForShortVideo = PKCameraUtils(sessionPreset: AVCaptureSessionPreset640x480)
//    static let sharedInstanceForLive = PKCameraUtils(sessionPreset: AVCaptureSessionPreset1280x720)
    
    static let sharedInstance = PKCameraUtils(sessionPreset: AVCaptureSessionPresetInputPriority)
    
    //MARK: - properties
    var previewView:UIView?
    
    //private
    private var videoCamera:GPUImageVideoCamera?
    private var customFilter:IFImageFilter?
    private var filterGroup:GPUImageFilterGroup?
    private var movieWriter:GPUImageMovieWriter?
    private var beautyFilter:GPUImageBeautifyFilter?
    
    var pathToMovie:String?
    
    var isRecording = false
    
    //MARK: - init
    private init(sessionPreset:String){
        super.init()
        
        let videoCamera = GPUImageVideoCamera(sessionPreset: sessionPreset, cameraPosition: .front)
        self.videoCamera = videoCamera
        videoCamera?.outputImageOrientation = .portrait
        
        let filteredVideoView = GPUImageView(frame: CGRect.zero)
        self.previewView = filteredVideoView
        
        
//        let customFilter = GPUImageFilter()
        
        // 裁剪滤镜
        let customFilter = IFSutroFilter()
        self.customFilter = customFilter
        
        // 自定义的美颜滤镜
        let beautyFilter = GPUImageBeautifyFilter()
        self.beautyFilter = beautyFilter
        // 滤镜分组
        let filterGroup = GPUImageFilterGroup()
        self.filterGroup = filterGroup
        
        /// 没有开美颜
        if (false) {
            videoCamera?.addTarget(customFilter)
            customFilter.addTarget(filteredVideoView)
        }else
        {/// 美颜和裁剪滤镜都加到滤镜组里
            customFilter.addTarget(beautyFilter)
            filterGroup.addTarget(customFilter)
            filterGroup.addTarget(beautyFilter)
            filterGroup.initialFilters = [customFilter]
            filterGroup.terminalFilter = beautyFilter
            filterGroup.forceProcessing(at: filteredVideoView.frame.size)
            filterGroup.useNextFrameForImageCapture()
            videoCamera?.addTarget(filterGroup)
            filterGroup.addTarget(filteredVideoView)
        }
        


        // Add the view somewhere so it's visible
//        videoCamera?.addTarget(customFilter)
//        customFilter.addTarget(filteredVideoView)
        
//        /// horizontallyMirrorFrontFacingCamera 属性 YES 代表前置的时候不是镜像
//        
//        videoCamera.horizontallyMirrorFrontFacingCamera = YES;
//        
//        videoCamera.horizontallyMirrorRearFacingCamera = NO;
        

    }
    
    //开始preview
    func startCapture() -> Void{
        videoCamera?.startCapture()
    }
    
    //结束preview
    func stopCapture() -> Void{
        videoCamera?.stopCapture()
    }
    
    //反转摄像头
    func toggle() -> Void{
        self.videoCamera?.rotateCamera()
    }
    
    //开始录制
    func startRecord() -> Void{
        self.isRecording = true
        // 根据时间生成路径 录制的视频会存储到该路径下 要唯一
//        [videoArray addObject:pathToMovie];
//        NSLog(@"%@",pathToMovie);
//        unlink(pathToMovie.utf8CString)
        pathToMovie = NSTemporaryDirectory()
        pathToMovie!.append("Movie.m4v")
        unlink((pathToMovie! as NSString).utf8String)
        let movieURL = URL(fileURLWithPath: pathToMovie!)

        
        //    movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(720, 720) fileType:AVFileTypeQuickTimeMovie outputSettings:videoSettings];
        let movieWriter = GPUImageMovieWriter(movieURL: movieURL, size: CGSize(width: 720, height: 720))
        self.movieWriter = movieWriter
        // audioSettings 一些音频配置
        
        /*
         
         AudioChannelLayout channelLayout;
         
         memset(&channelLayout, 0, sizeof(AudioChannelLayout));
         
         channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
         
         audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
         
         [ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,//制定编码算法
         
         [ NSNumber numberWithInt: 2 ], AVNumberOfChannelsKey,//声道
         
         [ NSNumber numberWithFloat: 16000.0 ], AVSampleRateKey,//采样率
         
         [ NSData dataWithBytes:&channelLayout length: sizeof( AudioChannelLayout ) ], AVChannelLayoutKey,
         
         [ NSNumber numberWithInt: 32000 ], AVEncoderBitRateKey,//编码率
         
         nil];
         
         */
//        movieWriter?.setHasAudioTrack(true, audioSettings: ["":""])
//        movieWriter?.hasAudioTrack = true
//        videoCamera?.addAudioInputsAndOutputs()
//        videoCamera?.audioEncodingTarget = movieWriter;
        
        //不加美颜
        if (false) {
            customFilter?.addTarget(movieWriter)
        }
        else {
            filterGroup?.addTarget(movieWriter)
        }
        
        movieWriter?.startRecording()
    }
    
    //结束录制
    func stopRecord() -> Void{
        
        self.isRecording = false
        
        movieWriter?.finishRecording()
        customFilter?.removeTarget(movieWriter)
        beautyFilter?.removeTarget(movieWriter)
        filterGroup?.removeTarget(movieWriter)
        videoCamera?.audioEncodingTarget = nil
    }
    
    //保存到本地 使用PhotoKit
    func save() -> Void{
        
    }
    
    //切换滤镜
    func setFilter(filter:IFImageFilter) -> Void{
        self.customFilter = filter
        
        //先移除所有target
        customFilter?.removeAllTargets()
        videoCamera?.removeAllTargets()
        filterGroup?.removeAllTargets()
        
        customFilter?.addTarget(beautyFilter)
        filterGroup?.addTarget(customFilter)
        filterGroup?.addTarget(beautyFilter)
        filterGroup?.initialFilters = [customFilter!]
        filterGroup?.terminalFilter = beautyFilter
        filterGroup?.forceProcessing(at: (self.previewView?.frame.size)!)
        filterGroup?.useNextFrameForImageCapture()
        videoCamera?.addTarget(filterGroup)
        filterGroup?.addTarget(self.previewView as! GPUImageInput!)
    }
    
    func setDefaultFilter() -> Void{
        
        //先移除所有target
        customFilter?.removeAllTargets()
        videoCamera?.removeAllTargets()
        filterGroup?.removeAllTargets()
        
        
        let image = R.image.f1()
        let lookupImageSource = GPUImagePicture(image: image)
        let lookupFilter = GPUImageLookupFilter()
        
//        filterGroup?.addFilter(lookupFilter)
        
        lookupImageSource?.addTarget(lookupFilter, atTextureLocation: 1)
        lookupImageSource?.processImage()
        
        
//        filterGroup?.initialFilters = [lookupFilter]
//        filterGroup?.terminalFilter = lookupFilter;
        
    
        filterGroup?.useNextFrameForImageCapture()
        customFilter?.addTarget(beautyFilter)
        filterGroup?.addTarget(lookupFilter)
        filterGroup?.addTarget(beautyFilter)
        filterGroup?.initialFilters = [lookupFilter]
        filterGroup?.terminalFilter = beautyFilter
        
        filterGroup?.forceProcessing(at: (self.previewView?.frame.size)!)
        
        videoCamera?.addTarget(filterGroup)
        filterGroup?.addTarget(self.previewView as! GPUImageInput!)
    }
    
//    //设置屏幕分辨率
//    func setResolution(captureSessionPreset:String) -> Void{
//        videoCamera?.captureSessionPreset = captureSessionPreset
//    }
    
    
    //MARK: - For test
    func isExist() -> Void{
        let fileManager = FileManager()
        print(fileManager.fileExists(atPath: self.pathToMovie!))
    }
    
    
    func play(From:UIViewController) -> Void{
        
        let url = URL(fileURLWithPath: self.pathToMovie!)
        let mediaPlayerViewController = RTSMediaPlayerViewController(contentURL: url)
        From.present(mediaPlayerViewController!, animated: true) { 
            
        }
    
    }
}
